﻿using System;
using umbraco.BusinessLogic;
using umbraco.cms.presentation.Trees;
using umbraco.interfaces;

namespace ProlificNotion.Umbraco.MediaImporter
{
    /// <summary>
    /// Registers events in Umbraco
    /// </summary>
    public class AppBase : umbraco.BusinessLogic.ApplicationBase
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="AppBase"/> class.
        /// </summary>
        public AppBase()
        {
            BaseContentTree.BeforeNodeRender += new BaseTree.BeforeNodeRenderEventHandler(BaseContentTree_BeforeNodeRender);
        }

        /// <summary>
        /// The BeforeNodeRender event of the BaseContentTree
        /// </summary>      
        /// <param name="sender">The sender.</param>
        /// <param name="node">The node.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void BaseContentTree_BeforeNodeRender(ref XmlTree sender, ref XmlTreeNode node, EventArgs e)
        {
            try
            {
                //- Make sure the menu is not null
                if (node.Menu != null && node.NodeType.ToLower() == "media")
                {
                    // Locate the index of the item after the sort menu item
                    int index = node.Menu.FindIndex(delegate(IAction a) { return a.Alias.ToLower() == "create"; }) + 1;
                    node.Menu.Insert(index, ImportMediaAction.Instance);
                }

            }
            catch (Exception ex)
            {
                Log.Add(LogTypes.Error, int.Parse(node.NodeID), "Error adding Import Media menu item to " + node.Text + " : " + ex.ToString());
            }
        }
    }
}
